package cgl.narada.util;

import java.io.InputStream;

/**
 * This class is to be used to launch native processes on the command line.
 * 
 * @author Shrideep Pallickara
 * 
 */

public class ProcessLauncher {

    private static final ProcessLauncher processLauncher = new ProcessLauncher();

    private static final String moduleName = "ProcessLauncher: ";

    private ProcessLauncher() {
    }

    public static ProcessLauncher getInstance() {
        return processLauncher;
    }

    /**
     * This method will try to execute a command that has been specified.
     * Specifically, we will also return any outputs that have been produced as
     * a result of the command's execution.
     * 
     * @param command
     * @return The output if any (if there is no output an empty String will be
     *         returned
     * @throws Exception
     */
    public String executeCommand(String command) throws Exception {
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec(command);

        String outputOfCommand = readStream(process.getInputStream());

        // check for problems in the execution of the command
        if (process.waitFor() != 0) {
            String errorReport = "Problems executing command ["
                + command + "]. Exit value = " + process.exitValue() + "\n" +
                outputOfCommand;

            throw new Exception(errorReport);
        }

        return outputOfCommand;
    }

    private String readStream(InputStream inputStream) throws Exception {
        StringBuffer buffer = new StringBuffer();
        int nextChar;
        
        while ((nextChar = inputStream.read()) != -1) {
            System.out.print((char) nextChar);
            buffer.append((char) nextChar);
        }
        return buffer.toString();
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        try {

            String command = "ls -al";
            ProcessLauncher processLauncher = ProcessLauncher.getInstance();
            String output;
            output = processLauncher.executeCommand(command);
            System.out.println(output);

            command = "ping 156.56.104.1";
            output = processLauncher.executeCommand(command);
            System.out.println(output);

        } catch (Exception ioe) {
            System.out.println(ioe.toString());
            ioe.printStackTrace();
        }
    }

}
